package com.ruoyi.system.service.impl;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.http.HttpUtils;
import com.ruoyi.system.domain.vo.MessageSubscribeVo;
import com.ruoyi.system.domain.vo.WeChatAccessTokenVo;
import com.ruoyi.system.domain.vo.WeChatSession;
import com.ruoyi.system.domain.vo.WeChatVo;
import com.ruoyi.system.service.ISysConfigService;
import com.ruoyi.system.service.IWeChatService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Date;
import java.util.concurrent.TimeUnit;

/**
 *
 * @author lisongtao
 * @date 2023/5/12 11:02
 */
@Service
public class WeChatServiceImpl implements IWeChatService {

    private static final String ACCESS_TOKEN_KEY = "wechat:access:token";

    private static final String ACCESS_TOKEN_KEY_PUBLIC = "wechat:access:token2";

    private static final Logger logger = LoggerFactory.getLogger(WeChatServiceImpl.class);

    @Autowired
    public RedisCache redisCache;
    @Autowired
    private ISysConfigService sysConfigService;

    /**
     * 微信登录
     * @date 2023/4/19 23:01
     * @param weChatVo
     * @return
     */
    @Override
    public String weChatLogin(WeChatVo weChatVo) {
        // 0.从系统参数中获取appId和secret
        String appId = sysConfigService.selectConfigByKey("wechat.access.appId");
        String appSecret = sysConfigService.selectConfigByKey("wechat.access.appSecret");
        logger.error(appId + "---------" + appSecret);

        // 1.接收小程序发送的code
        // 2.开发者服务器 登录凭证校验接口 appi + appsecret + code
        String requestUrl = "https://api.weixin.qq.com/sns/oauth2/access_token?" +
                "appid=" + appId + "&secret="+appSecret+"&code="+weChatVo.getCode()+"&grant_type=authorization_code";
        JSONObject sessionKeyOpenId = JSON.parseObject(HttpUtils.sendGet(requestUrl));
        System.out.println(sessionKeyOpenId);
        // 3.接收微信接口服务 获取返回的参数

        if (sessionKeyOpenId == null) {
            throw new ServiceException("访问微信服务器失败！");
        }

        String openid = sessionKeyOpenId.getString("openid");
        if (StringUtils.isEmpty(openid)) {
            throw new ServiceException("获取用户信息失败！");
        }
        return openid;
    }


    /**
     * 微信登录
     *
     *
     * @date 2023/4/19 23:01
     * @param weChatVo
     * @return
     */
    @Override
    public WeChatSession weChatLoginPlatform(WeChatVo weChatVo) {
        return null;
    }

    /**
     * 获取微信access_token
     * @date 2023/4/23 14:00
     * @return
     */
    @Override
    public synchronized String getWeChatAccessTokenVo() {
//        // 0.从系统参数中获取appId和secret
//        String appId = sysConfigService.selectConfigByKey("wechat:access:appId");
//        String appSecret = sysConfigService.selectConfigByKey("wechat:access:appSecret");
//
//        // 初次进入先在redis中获取accessToken值
//        String accessToken = redisCache.getCacheObject(ACCESS_TOKEN_KEY);
//        if (StringUtils.isNotBlank(accessToken)) {
//            return accessToken;
//        }
//        // 若不存在访问接口获取token
//        String requestUrl = " https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + appId + "&secret=" + appSecret;
//        JSONObject jsonObject = JSON.parseObject(HttpUtils.sendGet(requestUrl));
//        if (jsonObject == null) {
//            throw new ServiceException("获取微信accessToken失败！");
//        }
//        WeChatAccessTokenVo weChatAccessTokenVo = jsonObject.toJavaObject(WeChatAccessTokenVo.class);
//        if (StringUtils.isBlank(weChatAccessTokenVo.getAccess_token())) {
//            throw new ServiceException("获取微信accessToken失败！");
//        }
//        // 成功获取token，将token放入到redis中
//        String access_token = weChatAccessTokenVo.getAccess_token();
//        if (StringUtils.isBlank(access_token)) {
//            throw new ServiceException("获取微信accessToken失败！");
//        }
//        redisCache.setCacheObject(ACCESS_TOKEN_KEY, access_token, 7000, TimeUnit.SECONDS);
        return "access_token";
    }

    /**
     * 获取微信access_token
     * @date 2023/4/23 14:00
     * @return
     */
    @Override
    public synchronized String getPublicWeChatAccessTokenVo() {
        // 0.从系统参数中获取appId和secret
        String appId = "wxb79a72629dc529e3";
        String appSecret = "ac158c567004338632fba455180b492f";

        // 初次进入先在redis中获取accessToken值
        String accessToken = redisCache.getCacheObject(ACCESS_TOKEN_KEY_PUBLIC);
        if (StringUtils.isNotBlank(accessToken)) {
            return accessToken;
        }
        // 若不存在访问接口获取token
        String requestUrl = " https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + appId + "&secret=" + appSecret;
        JSONObject jsonObject = JSON.parseObject(HttpUtils.sendGet(requestUrl));
        if (jsonObject == null) {
            throw new ServiceException("获取微信accessToken失败！");
        }
        WeChatAccessTokenVo weChatAccessTokenVo = jsonObject.toJavaObject(WeChatAccessTokenVo.class);
        if (StringUtils.isBlank(weChatAccessTokenVo.getAccess_token())) {
            throw new ServiceException("获取微信accessToken失败！");
        }
        // 成功获取token，将token放入到redis中
        String access_token = weChatAccessTokenVo.getAccess_token();
        if (StringUtils.isBlank(access_token)) {
            throw new ServiceException("获取微信accessToken失败！");
        }
        redisCache.setCacheObject(ACCESS_TOKEN_KEY_PUBLIC, access_token, 7000, TimeUnit.SECONDS);
        return access_token;
    }

    /**
     * 获取发送消息模板id
     */
    @Override
    public Object getForemanTemplateId() {
        return sysConfigService.selectConfigByKey("wechat:foremanTemplate:id");
    }

    /**
     * 推送微信消息
     * @param messageSubscribeVo
     * @param pagepath
     */
    @Override
    public void pushWeChatMsg(MessageSubscribeVo messageSubscribeVo, String pagepath) {
        Object foremanTemplateId = getForemanTemplateId();
        if (foremanTemplateId == null) {
            return;
        }
        JSONObject miniprogram = new JSONObject();
//       beifen NmsJBs87wR6Mwbd2fzANZPJ-0j9iiWaO5a4G0f5Stq4
//        Ywe0Biv-mktMZFP2AypDzTIek16hHqbA1RGnCUxvnXU
        String programAppId = sysConfigService.selectConfigByKey("wechat:access:appId");
        miniprogram.put("appid", programAppId);
        miniprogram.put("pagepath", pagepath);
        String accessToken = getPublicWeChatAccessTokenVo();
        String requestUrl = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" + accessToken;
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("touser", messageSubscribeVo.getTouser());
//        jsonObject.put("touser", "o3NBS6TB0ANYa2Fxpa5Y0Xal0q6Q");
        jsonObject.put("template_id", foremanTemplateId.toString());
        jsonObject.put("miniprogram", miniprogram);
        JSONObject data = new JSONObject();
        JSONObject phrase2 = new JSONObject();
        phrase2.put("value", messageSubscribeVo.getPhrase2());
        data.put("phrase2", phrase2);
        JSONObject thing7 = new JSONObject();
        thing7.put("value", messageSubscribeVo.getThing7());
        data.put("thing7", thing7);
        JSONObject phone_number8 = new JSONObject();
        phone_number8.put("value", messageSubscribeVo.getPhone_number8());
        data.put("phone_number8", phone_number8);
        JSONObject thing14 = new JSONObject();
        thing14.put("value", messageSubscribeVo.getThing14());
        data.put("thing14", thing14);
        JSONObject time4 = new JSONObject();
        time4.put("value", DateUtils.dateTime2(new Date()));
        data.put("time4", time4);
        jsonObject.put("data", data);
        InputStream is = null;
        BufferedReader rd = null;
        String str = null;
        try {
            URL url = new URL(requestUrl);
            HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();
            httpConn.setRequestProperty("Content-Type", "text/xml; charset=\"UTF-8\"");
            httpConn.setRequestMethod("POST");
            httpConn.setDoInput(true);
            httpConn.setDoOutput(true);
            OutputStream out = httpConn.getOutputStream();
            OutputStreamWriter osw = new OutputStreamWriter(out, "UTF-8");
            logger.error(jsonObject.toString());
            osw.write(jsonObject.toString());
            osw.flush();
            osw.close();
            out.close();
            is = httpConn.getInputStream();
            rd = new BufferedReader(new InputStreamReader(is, "UTF-8"));

            while ((str = rd.readLine()) != null) {
                System.out.println("返回数据：" + str);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
